package com.muse.genericity;

import java.util.ArrayList;
import java.util.List;

import com.google.common.collect.Lists;

/**
 * 类型通配符
 */
public class TypeWildcard {

    private final static List<Integer> INTEGER_LIST = Lists.newArrayList(1, 2, 3, 4);

    private final static List<Object> OBJECT_LIST = Lists.newArrayList("a", 1, 'c', 6.0F, 100L, true);

    private final static List<String> STRING_LIST = Lists.newArrayList("x", "y", "z");

    public static void main(String[] args) {
        TypeWildcard typeWildcard = new TypeWildcard();
        typeWildcard.test1(INTEGER_LIST);
        System.out.println("------------test1 end-------------");

        // typeWildcard.test2(STRING_LIST);
        typeWildcard.test2(OBJECT_LIST);
        System.out.println("------------test2 end-------------");

        typeWildcard.test3(INTEGER_LIST);
        typeWildcard.test3(OBJECT_LIST);
        typeWildcard.test3(STRING_LIST);
        System.out.println("------------test3 end-------------");

        typeWildcard.test4(INTEGER_LIST);
        typeWildcard.test4(OBJECT_LIST);
        typeWildcard.test4(STRING_LIST);
        System.out.println("------------test4 end-------------");

        /** 上限通配符 */
        typeWildcard.test5(INTEGER_LIST);
        System.out.println("------------test5 end-------------");

        /** 下限通配符 */
        // typeWildcard.test6(INTEGER_LIST); 编译错误
        System.out.println("------------test6 end-------------");

    }

    public void test1(List list) {
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i) + " ");
        }
        System.out.println();
    }

    public void test2(List<Object> list) {
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i) + " ");
        }
        System.out.println();
    }

    public <T> void test3(List<T> list) {
        list.add(list.get(0));
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i) + " ");
        }
        System.out.println();
    }

    public void test4(List<?> list) {
        // list.add(list.get(0)); // 编译错误
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i) + " ");
        }
        System.out.println();
    }

    public void test5(List<? extends Number> list) {
        // list.add(list.get(0)); // 编译错误
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i) + " ");
        }
        System.out.println();
    }

    public void test6(List<? super Number> list) {
        // list.add(list.get(0)); // 编译错误
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i) + " ");
        }
        System.out.println();
    }
}


